package dao

import (
	"osiris/db"
	"osiris/logger"
	"osiris/model"

	peer "github.com/libp2p/go-libp2p/core/peer"
)

// GetPubKeyByID 从MYSQL中取出peerID对应的PubKey
//
//	@param peerID
//	@return model.PubKeyModel
//	@return error
func GetPubKeyByID(peerID peer.ID) (model.PubKeyModel, error) {
	var pubkeyModel model.PubKeyModel
	err := db.MySQL.Where("peerID = ?", peerID).First(&pubkeyModel).Error
	return pubkeyModel, err
}

// GetAllPubKeys 从MYSQL中取出所有节点的PubKey
//
//	@return []model.PubKeyModel
//	@return error
func GetAllPubKeys() ([]model.PubKeyModel, error) {
	var pubkeyModels []model.PubKeyModel
	err := db.MySQL.Find(&pubkeyModels).Error
	return pubkeyModels, err
}

// AddPubKeyByModel 通过PubKeyModel添加PubKey
//
//	@param model
//	@return error
func AddPubKeyByModel(model model.PubKeyModel) error {
	err := db.MySQL.Create(&model).Error
	if err != nil {
		logger.Error(map[string]interface{}{"[dao] [Add pubkey by model]": err})
		return err
	}

	logger.Info(map[string]interface{}{"[dao] [Add pubkey by model]": "success"})
	return nil
}

// SavePubKey Save update value in database, if the value doesn't have primary key, will insert it
//
//	@param model model.PubKeyModel
//	@return error
func SavePubKey(model model.PubKeyModel) error {
	err := db.MySQL.Save(&model).Error
	return err
}

func DeletePubKey(peerIDstr string) error {
	err := db.MySQL.Delete(&model.PubKeyModel{}, "peerID = ?", peerIDstr).Error
	return err
}
